<template>
  <div class="j-layout">
    <!-- 树 -->
    <div class="j-tree">
      <el-input
        placeholder="输入关键字"
        v-model="filterText"
        size="small"
        clearable
      >
      </el-input>

      <el-tree
        :expand-on-click-node="false"
        :highlight-current="true"
        class="filter-tree"
        :data="treeDatas"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="handleFilterNode"
        v-loading="treeLoading"
        @node-click="clickTreeNode"
        node-key="id"
        ref="tree"
      >
      </el-tree>
    </div>
    <!-- 内容 -->
    <div class="j-container">
      <!-- 搜索 -->
      <div class="j-container__search" v-if="searchShow">
        <el-form :inline="true" :model="query" size="small" label-width="68px">
          <el-form-item label="名称">
            <el-input
              v-model="query.name"
              placeholder="请输入名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadPages">查询</el-button>
            <el-button @click="clickReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="j-container__content">
        <!-- 工具栏 -->
        <div class="j-container__content__tool">
          <div>
            <el-button
              type="primary"
              size="small"
              @click="clickAdd"
              :disabled="treeNodeId == ''"
              >新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="clickDeletes"
              :disabled="rows.length == 0"
              >删除</el-button
            >
          </div>
          <div>
            <el-tooltip
              class="item"
              effect="dark"
              :content="searchShow ? '隐藏搜索' : '显示搜索'"
              placement="bottom"
            >
              <el-button
                icon="el-icon-view"
                circle
                size="mini"
                @click="clickSearchShow"
              ></el-button>
            </el-tooltip>
            <el-dropdown style="margin: 0px 10px" @command="handleCommand">
              <el-button icon="el-icon-menu" circle size="mini"></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="medium">大</el-dropdown-item>
                <el-dropdown-item command="small">中</el-dropdown-item>
                <el-dropdown-item command="mini">小</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-tooltip
              class="item"
              effect="dark"
              content="刷新"
              placement="bottom"
            >
              <el-button
                icon="el-icon-refresh"
                circle
                size="mini"
                @click="loadPages"
              ></el-button>
            </el-tooltip>
          </div>
        </div>
        <!-- 表格 -->
        <div class="j-container__content__table">
          <el-table
            @selection-change="changeTableSelection"
            ref="multipleTable"
            v-loading="loading"
            max-height="550"
            :highlight-current-row="true"
            :data="tableDatas"
            :border="true"
            style="width: 100%"
            :size="tableSize"
            :header-cell-style="{ textAlign: 'center', background: '#fafafa' }"
            :cell-style="{ textAlign: 'center' }"
          >
            <el-table-column type="selection" width="40"> </el-table-column>
            <el-table-column prop="name" label="名称" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template slot-scope="scope">
                <el-tag
                  size="mini"
                  :type="scope.row.status === true ? 'success' : 'danger'"
                  disable-transitions
                  >{{ scope.row.status ? "启用" : "停用" }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="序号" width="100" sortable>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="160"
              sortable
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="clickEidt(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  class="b-delete"
                  @click="clickDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="j-container__content__page">
          <el-pagination
            background
            @size-change="changePageSize"
            @current-change="changeCurrentPage"
            :hide-on-single-page="pageHidden"
            :current-page="query.pageNum"
            :page-sizes="[10, 30, 50, 100]"
            :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalPage"
          >
          </el-pagination>
        </div>
      </div>
      <!-- 新增/编辑 -->
      <div class="j-container__drawer">
        <el-drawer
          destroy-on-close
          @close="closeDrawer"
          :title="drawerTitle"
          :visible.sync="drawerDialog"
          direction="rtl"
          ref="drawer"
          close-on-press-escape
          size="30%"
        >
          <div>
            <el-form
              :model="drawerForm"
              :rules="drawerRules"
              ref="drawerForm"
              :inline="true"
              class="j-container__drawer__form"
              label-width="100px"
              status-icon
            >
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="drawerForm.name"
                  placeholder="请输入名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="majorName">
                <el-input
                  v-model="drawerForm.majorName"
                  placeholder="请输入负责人姓名"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="majorMobile">
                <el-input
                  v-model="drawerForm.majorMobile"
                  placeholder="请输入负责人手机"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="majorEmail">
                <el-input
                  v-model="drawerForm.majorEmail"
                  placeholder="请输入负责人邮箱"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="status" :required="true">
                <el-radio-group v-model="drawerForm.status">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">停用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="序号" prop="sort" :required="true">
                <el-input-number v-model="drawerForm.sort"></el-input-number>
              </el-form-item>
            </el-form>
            <div class="j-container__drawer__footer">
              <el-button
                type="primary"
                @click="clickSubmitForm('drawerForm')"
                size="small"
                >确定</el-button
              >
              <el-button @click="drawerDialog = false" size="small"
                >取消</el-button
              >
            </div>
          </div>
        </el-drawer>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listPageDepartments,
  listTreeDepartments,
  insertDepartment,
  updateDepartment,
  deleteDepartments,
  deleteDepartment,
} from "@/api/system/department";

export default {
  name: "DepartmentView",
  watch: {
    // 监听树检索
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      const regex =
        /^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\d{8}$/;
      if (value === "" || value == null) {
        callback();
      } else if (!regex.test(value)) {
        callback(new "手机号码格式不正确"());
      } else {
        callback();
      }
    };
    return {
      query: {
        name: "",
        parentId: "",
        pageSize: 10,
        pageNum: 1,
      },
      searchShow: true,
      tableDatas: [],
      totalPage: 0,
      pageHidden: true,
      loading: false,
      treeLoading: false,
      tableSize: "small",
      rows: [],
      drawerDialog: false,
      drawerTitle: "新增",
      drawerForm: {
        id: "",
        parentId: "",
        name: "",
        majorName: "",
        majorMobile: "",
        majorEmail: "",
        status: true,
        sort: 0,
      },
      drawerRules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { max: 50, message: "小于50个字符", trigger: "blur" },
        ],
        majorName: [{ max: 50, message: "小于50个字符", trigger: "blur" }],
        majorMobile: [{ validator: validateMobile, trigger: "blur" }],
        majorEmail: [
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
      },
      filterText: "",
      treeDatas: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      treeNodeId: "",
    };
  },
  created() {
    const t = this;
    t.loadTree();
    t.loadPages();
  },
  methods: {
    // 过滤树
    handleFilterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 选择树节点
    clickTreeNode(data) {
      const t = this;
      t.treeNodeId = data.id;
      t.query.parentId = data.id;
      t.drawerForm.parentId = data.id;
      if (t.treeNodeId === 1) {
        t.query.parentId = "";
      }
      t.loadPages();
    },
    // 查询树
    loadTree() {
      const t = this;
      t.treeLoading = true;
      setTimeout(() => {
        listTreeDepartments()
          .then((response) => {
            t.treeLoading = false;
            t.treeDatas = response.data;

            // 设置当前结点
            if (t.treeNodeId !== "") {
              t.$nextTick(() => {
                t.$refs.tree.setCurrentKey(t.treeNodeId);
              });
            }
          })
          .catch(() => {
            t.treeLoading = false;
          });
      }, 500);
    },
    // 分页查询列表
    loadPages() {
      const t = this;
      t.loading = true;
      setTimeout(() => {
        listPageDepartments(t.query)
          .then((response) => {
            t.loading = false;
            t.tableDatas = response.data.rows;
            t.totalPage = response.data.total;
            t.pageHidden = !t.totalPage > 0;
          })
          .catch(() => {
            t.loading = false;
          });
      }, 500);
    },
    // 搜索重置
    clickReset() {
      const t = this;
      t.query = {
        name: "",
        parentId: t.treeNodeId,
        pageSize: 10,
        pageNum: 1,
      };
      if (t.treeNodeId === 1) {
        t.query.parentId = "";
      }
      t.loadPages();
    },
    // 显示/隐藏搜索
    clickSearchShow() {
      this.searchShow = !this.searchShow;
    },
    // 修改表格显示大小
    handleCommand(command) {
      this.tableSize = command;
    },
    // 修改分页大小
    changePageSize(val) {
      const t = this;
      t.query.pageSize = val;
      t.loadPages();
    },
    // 分页
    changeCurrentPage(val) {
      const t = this;
      t.query.pageNum = val;
      t.loadPages();
    },
    // 改变删除按钮状态
    changeTableSelection(val) {
      this.rows = val;
    },
    // 批量删除
    clickDeletes() {
      const t = this;
      const rows = t.$refs.multipleTable.selection;

      t.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = rows.map((v) => v.id);
          deleteDepartments({ ids: params.join(",") })
            .then((response) => {
              t.handleNotice(response);
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 删除
    clickDelete(val) {
      const t = this;
      t.$confirm("此操作将删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteDepartment(val.id)
            .then((response) => {
              t.handleNotice(response);
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    // 新增
    clickAdd() {
      const t = this;
      t.drawerTitle = "新增";
      t.drawerDialog = true;
    },
    // 编辑
    clickEidt(val) {
      const t = this;
      t.drawerTitle = "编辑";
      const temp = JSON.parse(JSON.stringify(val));
      t.drawerForm = temp;
      t.drawerDialog = true;
    },
    // 抽屉关闭事件
    closeDrawer() {
      const t = this;
      t.$refs.drawerForm.resetFields();
      t.drawerForm = {
        id: "",
        parentId: t.treeNodeId,
        name: "",
        majorName: "",
        majorMobile: "",
        majorEmail: "",
        status: true,
        sort: 0,
      };
    },
    // 保存
    clickSubmitForm(formName) {
      const t = this;
      t.$refs[formName].validate((valid) => {
        if (valid) {
          if (t.drawerForm.id === "") {
            // 新增
            insertDepartment(t.drawerForm)
              .then((response) => {
                t.handleNotice(response);
                t.drawerDialog = false;
              })
              .catch(() => {});
          } else {
            // 编辑
            updateDepartment(t.drawerForm)
              .then((response) => {
                t.handleNotice(response);
                t.drawerDialog = false;
              })
              .catch(() => {});
          }
        } else {
          return false;
        }
      });
    },
    handleNotice(response) {
      const t = this;
      t.$notify({
        title: "成功",
        message: response.message,
        type: "success",
        position: "bottom-left",
        duration: 2000,
      });
      t.loadPages();
      t.loadTree();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/layout.scss";
</style>
